package com.chuanke.ckfamily.service.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.kid.server.libary.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

/**
 *  传客RSA解密工具类
 *
 * Created by xiaoxia on 2017/8/24 15:36.
 */
public class SignUtil {
    // 解密  盐值
    public static final String SIGN_DECRYPT = "CK";
    // 获取publickey传客服务器接口url
    public static final String URL = "/api/rsa/get_public_key";
    private static final Logger logger = LoggerFactory.getLogger(SignUtil.class);
    /**
     *  从request中获取sign（字典排序）
     * @param request
     * @return elect_id=158835&money=145&type=1&uid=100526&sign=盐值
     */
    public static String getSign(HttpServletRequest request) {
        List<String> names = new ArrayList<>();
        Enumeration<String> paramNameEnumeration = request.getParameterNames();
        while (paramNameEnumeration.hasMoreElements()) {
            String name = paramNameEnumeration.nextElement();
            if (!"sign".equals(name)) {
                names.add(name);
            }
        }
        Collections.sort(names);
        StringBuilder contextBuilder = new StringBuilder();
        Iterator<String> iterator = names.iterator();
//        if(iterator.hasNext()){
//            String param = iterator.next();
//        }
        while (iterator.hasNext()){
            String param = iterator.next();
            if(request.getParameter(param)!=null&&!request.getParameter(param).trim().equals("")){
                contextBuilder.append(param+"="+request.getParameter(param)+"&");
            }
        }
        contextBuilder.append("sign="+SIGN_DECRYPT);
        logger.debug("get sian by request =================> result={}",contextBuilder.toString());
        return contextBuilder.toString();
    }

    /**
     *  获取传客服务器的publickey字符串
     * @return
     */
    public static String getEncryptSign() throws IOException {
        // 请求拿到 公钥
        String responseContext = HttpUtil.getInstance().postHttpRequest(CkServerUtil.CKHOST + URL,"");
        logger.debug("get pubglic key=========>{}", responseContext);
        return responseContext;
    }

    /**
     * 得到公钥
     * @param key 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }
}
